const { Review } = require('../models');

// 创建评价
exports.createReview = async (req, res) => {
    try {
        const { orderId, rating, comment } = req.body;
        const userId = req.user.userinfo.id;
        const { carId } = req.order;  // 从验证器中获取订单信息

        const review = await Review.create({
            userId,
            carId,
            orderId,
            rating,
            comment
        });

        res.status(201).json({
            success: true,
            message: '评价成功',
            data: review
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '评价失败',
            error: error.message
        });
    }
};

// 获取车辆的所有评价
exports.getCarReviews = async (req, res) => {
    try {
        const { carId } = req.params;
        const reviews = await Review.find({ carId })
            .populate('userId', 'username')
            .sort({ createdAt: -1 });

        res.status(200).json({
            success: true,
            data: reviews
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取评价失败',
            error: error.message
        });
    }
};

// 获取用户的所有评价
exports.getUserReviews = async (req, res) => {
    try {
        const userId = req.user.userinfo.id;
        const { page = 1, limit = 10 } = req.query;

        const reviews = await Review.find({ userId })
            .populate('carId', 'brand model coverImage')
            .populate('orderId', 'orderNumber')
            .sort({ createdAt: -1 })
            .skip((page - 1) * parseInt(limit))
            .limit(parseInt(limit));

        const total = await Review.countDocuments({ userId });

        res.status(200).json({
            success: true,
            data: {
                reviews,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / parseInt(limit))
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取评价失败',
            error: error.message

        });
    }
};

// 获取单条评价详情 (用户只能查看自己的评价)
exports.getReviewDetails = async (req, res) => {
    try {
        const userId = req.user.userinfo.id;
        const { id: reviewId } = req.params;

        const review = await Review.findOne({ _id: reviewId, userId })
            .populate('carId', 'brand model coverImage year color') // 增加了年份和颜色
            .populate('orderId', 'orderNumber startTime endTime totalAmount'); // 增加了订单更多信息

        if (!review) {
            return res.status(404).json({
                success: false,
                message: '评价不存在或无权查看'
            });
        }

        res.status(200).json({
            success: true,
            data: review
        });
    } catch (error) {
        // 如果ID格式不正确，Mongoose会抛出CastError
        if (error.name === 'CastError') {
            return res.status(400).json({
                success: false,
                message: '无效的评价ID格式'
            });
        }
        res.status(500).json({
            success: false,
            message: '获取评价详情失败',
            error: error.message
        });
    }
}; 